package com.doupi.partner.manager.authenticator.filter;

import com.doupi.partner.dal.model.Administrator;
import com.doupi.partner.manager.authenticator.athuc.AutoLoginToken;
import com.doupi.partner.model.PartnerRelation;
import com.doupi.partner.service.*;
import com.doupi.partner.util.AssertUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * web 过滤器创建{@link AutoLoginToken AutoLoginToken}
 *
 * @author Alvin Wang
 * @version 1.0.0 on 2017-04-04
 */
public class AutoLoginAuthenticationFilter extends BaseAuthenticationFilter {

	@Autowired
	public AutoLoginAuthenticationFilter(AdministratorPermissionService administratorPermissionService, AdministratorHasRoleService administratorHasRoleService,
			AdministratorRoleHasPermissionService administratorRoleHasPermissionService, PartnerRelationService partnerRelationService, AdministratorService administratorService) {
		super(administratorPermissionService, administratorHasRoleService, administratorRoleHasPermissionService, partnerRelationService, administratorService);
	}

	public AutoLoginAuthenticationFilter() {
		this(null, null, null, null, null);
	}

	@Override
	protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
		String openId = request.getParameter("openId");
		PartnerRelation partnerRelation = partnerRelationService.selectByOpenId(openId);
		AssertUtils.assertNotNull(partnerRelation, "自动登录失败");
		Administrator administrator = administratorService.selectByPrimaryKey(partnerRelation.getAdministratorId());
		String username = administrator.getMobile();
		String host = getHost(request);
		boolean rememberMe = isRememberMe(request);
		return new AutoLoginToken(username, rememberMe, host);
	}

	@Override
	protected boolean isLoginRequest(ServletRequest request, ServletResponse response) {
		return true;
	}

	@Override
	protected boolean isLoginSubmission(ServletRequest request, ServletResponse response) {
		return true;
	}
}
